﻿using System;

namespace Gmantis.Controls.DataGrid
{
    internal interface IScrollStrategy
    {
        // Events
        event EventHandler Changed;

        // Methods
        int GetItemIndexFromScrollPosition(double scrollPosition, out double offset);
        double GetScrollPositionFromItemIndex(int startingItemIndex);

        // Properties
        double ExtentLength { get; }
    }

    internal abstract class DataGridVariableScrollStrategy : IScrollStrategy
    {
        // Fields
        private AggregatingTable<double, DoubleSumAggregator> _table;

        // Events
        public event EventHandler Changed;

        // Methods
        protected DataGridVariableScrollStrategy()
        {
        }

        protected abstract AggregatingTable<double, DoubleSumAggregator> BuildTable();
        protected virtual void DestroyTable()
        {
            this._table = null;
        }

        public virtual int GetItemIndexFromScrollPosition(double scrollPosition, out double offset)
        {
            IndexOffset<double> offset2 = this.Table.FindByLength(scrollPosition);
            offset = Math.Min((double)0.0, (double)(offset2.Offset - scrollPosition));
            return offset2.Index;
        }

        public virtual double GetScrollPositionFromItemIndex(int startIndex)
        {
            return this.Table.FindByIndex(startIndex).Offset;
        }

        protected void RaiseOnChanged()
        {
            if (this.Changed != null)
            {
                this.Changed(this, new EventArgs());
            }
        }

        // Properties
        public virtual double ExtentLength
        {
            get
            {
                return this.Table.TotalLength();
            }
        }

        protected AggregatingTable<double, DoubleSumAggregator> Table
        {
            get
            {
                if (this._table == null)
                {
                    this._table = this.BuildTable();
                    this.RaiseOnChanged();
                }
                return this._table;
            }
        }
    }
}
